package com.mangatta.cloud.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.amazonaws.services.cloudwatch.model.Datapoint;
import com.mangatta.cloud.alarm.AlarmConfiguration;

import java.util.List;

public class InstanceStatusDao extends DbHelper {
    private static final String TAG = InstanceStatusDao.class.getSimpleName();

    public InstanceStatusDao(Context context) {
        super(context);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG, "Created table");
        super.onCreate(db);//create tables.
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d(TAG, "on Updated");
    }

    public void persistInstanceStatus(String instanceId, AlarmConfiguration alarmConfig, List<Datapoint> dataPoints) {
        if (instanceId == null || alarmConfig == null || dataPoints == null || dataPoints.size() == 0) {
            return;
        }
        SQLiteDatabase database = getWritableDatabase();
        try {
            ContentValues contentValues = new ContentValues();
            for (Datapoint datapoint : dataPoints) {
                contentValues.clear();
                contentValues.put(InstanceStatusTable.C_INSTANCE, instanceId);
                contentValues.put(InstanceStatusTable.C_METRIC, alarmConfig.getMetric().getName());
                contentValues.put(InstanceStatusTable.C_VALUE, datapoint.getMaximum());
                contentValues.put(InstanceStatusTable.C_STATISTIC, alarmConfig.getStatistic().getName());
                contentValues.put(InstanceStatusTable.C_UNIT, datapoint.getUnit());
                contentValues.put(InstanceStatusTable.C_SAMPLED_AT, datapoint.getTimestamp().getTime());
                contentValues.put(InstanceStatusTable.C_SAMPLE_COUNT, datapoint.getSampleCount());
                database.insertWithOnConflict(InstanceStatusTable.TABLE_INSTANCE_STATUSES, null, contentValues,
                        SQLiteDatabase.CONFLICT_IGNORE);
            }
        } finally {
            database.close();
        }
    }
}
